import React, { PureComponent, Fragment, Suspense } from 'react';
import * as ol from 'ol';

window.ol = ol;
import { OlMap, spaceLineType } from '@/utils/olmap';
import { connect } from 'dva';
import { JSONPARSE, colorRgb } from '@/utils/tools';
import classNames from 'classnames';
import { featureController } from '@/utils/featureController';
import {
  Card,
  Checkbox,
  Row,
  Col,
  Select,
  Drawer,
  Icon,
  Button,
  Modal,
  message,
  Input,
} from 'antd';
import ListCardList from '@/components/MyPublic/ListCardList';
import ListCardDetail from '@/components/MyPublic/ListCardList/detail';
import LabelPopup from '@/components/MyPublic/LabelPopup';
import IconFont from '@/components/IconFont';
import _ from 'lodash';
import Text from 'ol/style/Text';
import { Icon as OlIcon, Fill, Stroke, Style } from 'ol/style';

import router from 'umi/router';
import PageLoading from '@/components/PageLoading';
import debounce from 'lodash/debounce';
import RootMap from './mapList';
import CustomerTree from './CustomerTree';
import styles from './style.less';

import ol_render3D from '@/assets/ol3d/Render3D';

console.log('ol', ol, window.ol);

const { Search } = Input;
const CheckboxGroup = Checkbox.Group;

const CamerabackForm = React.lazy(() => import('./CamerabackForm'));


const fenceStyles = [
  new Style({
    stroke: new Stroke({
      color: colorRgb('#e9001b', 1),
      width: 3,
    }),
    fill: new Fill({
      color: colorRgb('#e9001b', 0.5),
    }),
  }),
];

const plainOptions = [
  {
    label: '人员',
    value: 'people',
    icon: 'icon-ren',
  },
  {
    label: '摄像头',
    value: 'camera',
    icon: 'icon-shexiangtou1',
  },
  {
    label: '报警',
    value: 'alarm',
    icon: 'icon-gaojing-copy',
  },
  {
    label: '电子围栏',
    value: 'fence',
    icon: 'icon-duobianxingweilan-copy',
  },
  {
    label: '信标',
    value: 'beacon',
    icon: 'icon-xinbiao',
  },
  {
    label: '基站',
    value: 'station',
    icon: 'icon-jizhanxinhao',
  },
];
const treeType = [
  { id: 1, name: '人员', value: 'people' },
  { id: 2, name: '摄像头', value: 'camera' },
  { id: 3, name: '报警', value: 'alarm' },
  { id: 4, name: '电子围栏', value: 'fence' },
  /*  {id: 5, name: '信标'},
    {id: 6, name: '基站'}, */
];

const labelState = {
  /* 1: '胸牌',
  2: '手环',
  3: '安全帽',
  4: '资产',
  5: '车载', */
  6: {
    val: 'beacon',
    featureType: 4,
    image: '/element/xinbiao.png',
    image_dian: '/element/xinbiao_dian.png',
    op: { scale: 0.25 },
  },
  7: { val: 'station', featureType: 4, image: '/element/jizhan.png' },
  8: { val: 'camera', featureType: 4, image: '/element/camera.png' },
  9: { val: 'fence', featureType: 2 },
  10: { val: 'alarm', featureType: 4, image: '/element/gaojing.png' },
};

const treeTypeObj = {
  1: '人员',
  2: '人员',
  8: '摄像头',
  10: '报警',
  9: '电子围栏',
  6: '信标',
  7: '基站',
};
const defaultCheckedList = plainOptions.map(item => item.value);

class LayerCheck extends PureComponent {
  state = {
    checkedList: defaultCheckedList,
    indeterminate: false,
    checkAll: true,
  };

  onChange = checkedList => {
    const { handlerChange } = this.props;
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && checkedList.length < plainOptions.length,
      checkAll: checkedList.length === plainOptions.length,
    });
    if (handlerChange) handlerChange(checkedList);
  };

  onCheckAllChange = e => {
    const { handlerChange } = this.props;
    this.setState(
      {
        checkedList: e.target.checked ? plainOptions.map(item => item.value) : [],
        indeterminate: false,
        checkAll: e.target.checked,
      },
      () => {
        if (handlerChange) handlerChange(this.state.checkedList);
      },
    );
  };

  render() {
    const { value, handlerChange, ...rest } = this.props;
    return (
      <div className={styles.layer_check_box} {...rest}>
        <div>
          <Checkbox
            indeterminate={this.state.indeterminate}
            onChange={this.onCheckAllChange}
            checked={this.state.checkAll}
          >
            全部
          </Checkbox>
        </div>
        <CheckboxGroup
          // options={plainOptions}
          value={value}
          onChange={this.onChange}
        >
          {plainOptions.map((item, index) => (
            <div key={index}>
              <Checkbox value={item.value}>
                <IconFont
                  type={item.icon}
                  style={{
                    fontSize: 16,
                    marginRight: 4,
                  }}
                />
                {item.label}
              </Checkbox>
            </div>
          ))}
        </CheckboxGroup>
      </div>
    );
  }
}


@connect(({ main, loading, playback }) => ({
  main,
  playback,
  loading: loading.models.main,
}))
class Index extends PureComponent {
  state = {
    treeRecord: undefined,
    selectedKeys: null,
    nodeType: 1,
    drawerVisible: false,
    isFollow: false,
    formValues: {
      page_no: 0,
      page_size: 5,
    },
    // peoplePopupMsg: undefined,
    popup: { type: undefined, data: [] },
    checkedList: defaultCheckedList,
    videoMap: {},
    modalType: undefined,
    modalValues: undefined,
    fullScreen: false,
    showLayerCheck: false,
    labelPopup: {}
  };

  roomFeatureIds = [];

  intervalCount = 1;

  baseLayer;

  map;

  labelLayers = {
    camera: {},
    fence: {},
    beacon: {},
    station: {},
  };

  nowNodeId = null;

  isReload = true;

  constructor() {
    super();
    this.handleSNSearch = debounce(this.handleSNSearch, 250);
  }

  componentDidMount() {
    this.fetchFloors();
    this.monitorSearch({}, first => {
      this.setState(
        {
          treeRecord: first,
        },
        () => {
          this.nowNodeId = first.id;
          this.queryMap(first.id);
          this.queryMapTag(first.id);

          this.fetchLabel(first.id);
          // this.queryNodeData();
        },
      );
    });

    this.initMap();
    this.mapEvent();

    this.bindFullscreenListener();
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (this.props.main.monitorData !== prevProps.main.monitorData) {
      this.setMonitor();
    }
  }

  componentWillUnmount() {
    clearTimeout(this.intervalCount);
    this.monitorSearch = null;
    clearTimeout(this.labelDetailTime);
    this.getLabelDetail = null;
    try {
      this.unBindFullscreenListener();
    } catch (e) {
      console.warn(e);
    }
  }

  setMonitor = () => {
    const {
      main: { monitorData, pointIdObj },
    } = this.props;

    monitorData.forEach(data => {
      if (data.type !== 10) {
        const { treeRecord } = this.state;
        if (treeRecord && (treeRecord.id === data.floor_id || treeRecord.id === data.node_id)) {
          const _data = { ...data };

          if (this.mm_id) {
            const ff = this.layerSource.getFeatureById(this.mm_id);
            const geo = ff.getGeometry(); // feture是几何元素
            const lngLat =
              data.move_x && data.move_y ? [data.move_x, data.move_y] : [data.x, data.y];
            const isIn = geo.intersectsCoordinate(lngLat);

            if (!isIn) {
              let min = null;

              const coordinates = geo.getCoordinates();

              if (coordinates[0]) {
                coordinates[0].forEach(item => {
                  const distance = Math.sqrt(
                    Math.pow(lngLat[0] - item[0], 2) + Math.pow(lngLat[1] - item[1], 2),
                  ); // getDistance([data.x,data.y],[item[0],item[1]]);

                  if (min === null || min > distance) {
                    min = distance;
                    _data.move_x = item[0];
                    _data.move_y = item[1];
                    _data.x = item[0];
                    _data.y = item[1];
                  }
                });
              }
            }
          }

          this.plane.initFlight(_data);
          //
        } // 楼层一至 或在同一个节点时添加
        if (
          this.plane.selectPlane &&
          this.plane.selectPlane.id === data.id &&
          this.state.isFollow
        ) {
          // 判断是否跟踪
          if (treeRecord && treeRecord.floor_id !== data.floor_id) {
            // 跟踪时楼层不一至
            const {
              main: {
                treeData: { treeObject },
              },
            } = this.props;
            this.treeNodeChange(treeObject[data.floor_id], () => {
              /* this.showPopup({
                id: data.id,
                type: data.type,
                popupType: 'people',
                coordinate: [data.x, data.y]
              }); */
            });
          }
        } else if (
          treeRecord &&
          treeRecord.id !== data.floor_id &&
          treeRecord.id !== data.node_id
        ) {
          // 跟踪时楼层不一至
          this.plane.removeFeature(data.id);
        }
      } else {
        const label = labelState[data.type];
        const source = this.labelLayers.alarm.getSource();
        const newFeature = spaceLineType.getFeature(
          [data.x, data.y],
          label.featureType,
          0,
          label.image,
        );
        newFeature.setId(data.id);
        source.addFeature(newFeature);
      }
    });
    Object.keys(this.plane.flights).forEach(key => {
      if (!pointIdObj[key]) {
        this.plane.removeFeature(key);
      }
    });
  };

  fetchFloors = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'main/fetchFloors',
    });
  };

  /**
   * 初始化地图组件
   */
  initMap() {
    this.map = new OlMap('map', {});
    this.mapLayer = this.map.createLayer('Layer', 10);
    this.layerSource = this.mapLayer.getSource();
    this.mapTagLayer = this.map.createLayer('LayerTag', 10);
    this.layerTagSource = this.mapTagLayer.getSource();
    let r3D2 = new ol_render3D({
      height: (feature) => {
        let properties = feature.getProperties();
        return properties.height || 0
      },
      maxResolution: 500,
      layer: this.mapLayer,
      style: new Style({
        stroke: new Stroke({
          color: '#40A4FB',
          width: 0,
        }),
        fill: new Fill({
          color: colorRgb('#40A4FB', 0.2),
        }),
        zIndex: 50,
      })
    });

    // this.mapLayer.setRender3D(r3D2);
    /*
        this.mapLayer.setStyle((style)=>{

          return style
        })
    */

    /*    this.baseLayer = this.map.createLayer('baseLayer', 500,styleFunction);
        this.baseLayerSource = this.baseLayer.getSource(); */

    // this.map.addLayer(this.baseLayer);
    this.plane = new featureController({
      map: this.map,
      ws: null,
      layerName: 'people',
      img: '/element/ren.png',
      zIndex: 500,
    });
    // this.plane.layer.setVisible(false);
    this.labelLayers = {
      camera: this.map.createLayer('camera', 100),
      fence: this.map.createLayer('fence', 100),
      beacon: this.map.createLayer('beacon', 100),
      station: this.map.createLayer('station', 100),
      people: this.plane.layer,
      alarm: this.map.createLayer('alarm', 100),
    };
  }

  mapEvent = () => {
    this.map.on('click', evt => {
      if (evt.map.hasFeatureAtPixel(evt.pixel)) {
        let typeName = '';

        const feature = evt.map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
          if (layer) {
            typeName = layer.get('typeName');
            if (typeName !== 'baseLayer') {
              return feature;
            }
            return null;
          }
          return null;
        });

        if (feature) {
          let id;
          this.setState({
            isFollow: false,
          });
          switch (typeName) {
            case 'spaceLines':
              break;
            case 'people':
              id = feature.getId();
              if (this.plane.selectPlane && this.plane.selectPlane.id === id) {
                // this.plane.setTargetLine(id, false);
                this.plane.selectPlane = {};
                this.plane.source.changed();
                this.closePopup();
                return;
              }
              this.plane.setSelectFeature(feature);
              this.plane.setfollow(false);

              const select = this.plane.selectPlane;
              if (select && select.id) {
                this.showPopup({
                  id: select.id,
                  type: 1,
                });
              }
              this.plane.refreshLayer();
              break;
            case 'camera':
              id = feature.getId();
              this.showPopup({ id, type: 8 });
              break;
            case 'alarm':
              id = feature.getId();
              this.showPopup({ id, type: 10 });
              break;
            case 'beacon':
              id = feature.getId();
              this.showPopup({ id, type: 6 });
              break;
            case 'station':
              id = feature.getId();
              this.showPopup({ id, type: 7 });
              break;
            case 'fence':
              id = feature.getId();
              this.showPopup({ id, type: 9 });
              break;
          }
        }
      }
    });
  };

  monitorSearch = (params, callback) => {
    const { dispatch } = this.props;
    const { nodeType, treeRecord, formValues } = this.state;
    clearTimeout(this.intervalCount);
    dispatch({
      type: 'main/monitorSearch',
      payload: {
        ...params,
        type: nodeType,
        node_id: treeRecord ? treeRecord.id : undefined,
        ...formValues,
      },
      callback,
    }).then(() => {
      if (this.monitorSearch) {
        this.intervalCount = setTimeout(() => {
          this.monitorSearch();
        }, 1000);
      }
    });
  };

  /**
   * 获取当前节点 标签
   * @param node_id
   */
  fetchLabel = node_id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'main/fetchLabel',
      payload: {
        node_id,
      },
      callback: list => {
        list.forEach(item => {
          const label = labelState[item.type];
          if (label) {
            const source = this.labelLayers[label.val].getSource();
            const path = JSONPARSE(item.text, []);
            if (path && path.length > 0) {
              let newFeature;
              if (label.featureType === 4) {
                const img = item.alarm_type === 3 ? label.image_dian : label.image;
                const op = item.alarm_type === 3 ? { size: [64, 128] } : {};
                newFeature = spaceLineType.getFeature(path[0], label.featureType, 0, img, {
                  ...op,
                  ...label.op,
                });
              }
              if (label.featureType === 2)
                newFeature = spaceLineType.getFeature(path, label.featureType);
              newFeature.setId(item.id);
              newFeature.setProperties(item);
              if (label.val === 'fence') {
                newFeature.setStyle(fenceStyles);
              }
              source.addFeature(newFeature);
            }
          }
        });
      },
    });
  };

  visitorNum = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'main/visitorNum',
    });
  };

  /**
   * 获取 当前楼层 地图layer
   * @param node_id
   */
  queryMap = node_id => {
    const { dispatch } = this.props;
    this.mm_id = null;
    this.layerSource.clear();
    dispatch({
      type: 'main/detail',
      payload: {
        node_id,
      },
      callback: list => {
        this.renderRoom(list, node_id);
      },
    });
  };

  queryMapTag = node_id => {
    const { dispatch } = this.props;
    this.layerTagSource.clear();
    dispatch({
      type: 'main/tagDetail',
      payload: {
        node_id,
      },
      callback: list => {
        this.layerTagSource.clear();
        this.renderTag(list);
        /* if (node_id === 1) {
          let newFeature = spaceLineType.getFeature([334.66, -729.04], 4);
          let style = new Style({
            zIndex: 50
          });

          style.setImage(new OlIcon({
            size: [200, 200],
            scale: 0.48,
            src: `/favicon.png`
          }));
          newFeature.setStyle(style);
          this.layerTagSource.addFeature(newFeature);
        } */
      },
    });
  };

  labelDetail = (params, callback) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'main/labelDetail',
      payload: {
        ...params,
      },
      callback,
    });
  };

  /**
   * 树节点点击事件
   * @param recode
   * @param callback
   */
  setTreeSelected = (recode = {}, callback) => {
    // this.handleTargetDrawerVisible(true);
    if (this.state.isFollow && this.plane.selectPlane.id) {
      this.track(this.plane.selectPlane.id, false);
      this.plane.selectPlane = {};
    }
    this.treeNodeChange(recode, callback);
  };

  treeNodeChange = (recode, callback) => {
    const { treeRecord } = this.state;
    const {
      main: {
        treeData: { treeObject },
      },
    } = this.props;
    this.nowNodeId = recode.id;
    if (treeRecord === undefined || treeRecord.id !== recode.id || this.isReload) {
      this.closePopup();
      this.setState(
        {
          treeRecord: recode,
          selectedKeys: [recode.id.toString()],
          formValues: {
            ...this.state.formValues,
            page_no: 0,
          },
        },
        () => {
          this.isReload = false;

          const floor = recode.floor_id ? treeObject[recode.floor_id] : recode;

          if (treeRecord && treeRecord.floor_id !== floor.id) {
            this.queryMap(floor.id);
            this.queryMapTag(floor.id);
          }
          this.mapLayer.changed();
          //  this.queryNodeData();
          Object.keys(this.labelLayers).forEach(key => this.labelLayers[key].getSource().clear());
          this.plane.clear();
          this.fetchLabel(recode.id);
          /*     Object.keys(this.state.popup).forEach(key => {
               this.closePopup(key);
             }); */
          if (callback) callback();
        },
      );
    }
  };

  /**
   * 用详细列表
   * 返回对应节点的设备等数据
   */
  queryNodeData = param => {
    const { dispatch } = this.props;
    const { nodeType, treeRecord } = this.state;
    if (treeRecord && treeRecord.id) {
      dispatch({
        type: 'main/nodeSearch',
        payload: {
          ...param,
          type: nodeType,
          node_id: treeRecord.id,
        },
      });
    }
  };

  mm_id;

  //
  renderRoom(nodeMapList, node_id) {
    this.layerSource.clear();
    nodeMapList.forEach(item => {
      const roomInfoList = JSONPARSE(item.content, []);
      roomInfoList.forEach((featuresOPS, index) => {
        if (!featuresOPS.path) return;
        const { path } = featuresOPS;
        const newFeature = spaceLineType.getFeature(path, 2);
        const featureId = `room_${node_id}_${item.id}_${index}`;

        if (featuresOPS.checked) {
          this.mm_id = featureId;
        }

        newFeature.setId(featureId);
        newFeature.setProperties(featuresOPS);
        if (featuresOPS) {
          newFeature.setStyle(feature => {
            const aa = feature.getProperties();
            const style = new Style({
              stroke: new Stroke({
                color: '#40A4FB',
                width: 1,
              }),
              fill: new Fill({
                color: colorRgb('#40A4FB', 0.2),
              }),
              zIndex: 50,
            });
            if (
              featuresOPS.borderColor &&
              /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(featuresOPS.borderColor)
            ) {
              style.setStroke(
                new Stroke({
                  color: featuresOPS.borderColor,
                  width: featuresOPS.width,
                }),
              );
            }
            if (featuresOPS.color && /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(featuresOPS.color)) {
              style.setFill(
                new Fill({
                  color: colorRgb(featuresOPS.color, featuresOPS.opacity || 1),
                }),
              );
            }
            if (this.nowNodeId === aa.node) {
              style.setFill(
                new Fill({
                  color: colorRgb('#b700ff', 1),
                }),
              );
            }
            return style;
          });
        }
        this.roomFeatureIds.push(featureId);
        this.layerSource.addFeature(newFeature);
      });
    });

    const extent = this.layerSource.getExtent();
    if (!isNaN(extent[0]) && extent[0] !== Infinity)
      this.map.fit(extent, { padding: [80, 80, 80, 80] });
  }

  renderTag(nodeMapList) {
    nodeMapList.forEach(item => {
      const roomInfoList = JSONPARSE(item.content, []);
      roomInfoList.forEach((featuresOPS, index) => {
        if (!featuresOPS.path) return;
        const { path } = featuresOPS;
        const newFeature = spaceLineType.getFeature(path[0], 4);
        const featureId = `tag_${item.node_id}_${item.id}_${index}`;
        newFeature.setId(featureId);
        if (featuresOPS && (featuresOPS.type || featuresOPS.label)) {
          const style = new Style({
            zIndex: 50,
          });

          if (featuresOPS.type) {
            style.setImage(
              new OlIcon({
                size: [36, 36],
                scale: 0.7,
                src: `/element/${featuresOPS.type}.png`,
              }),
            );
          }
          if (featuresOPS.label) {
            style.setText(
              new Text({
                font: '14px  sans-serif',
                offsetX: featuresOPS.type ? 15 : 0,
                text: featuresOPS.label,
                textAlign: 'left',
              }),
            );
          }
          newFeature.setStyle(() => style);
        }
        this.roomFeatureIds.push(featureId);
        this.layerTagSource.addFeature(newFeature);
      });
    });
  }

  handleNodeTypeChange = val => {
    this.setState(
      {
        nodeType: val,
        drawerVisible: false,
      },
      () => {
        this.isReload = true;
        const { checkedList } = this.state;
        treeType.forEach(item => {
          if (val === item.id) {
            checkedList.push(item.value);
          }
        });
        this.handlerLayerCheckChange([...new Set(checkedList)]);

        /*  this.query();
        this.queryNodeData(); */
      },
    );
  };

  handleTargetDrawerVisible = flag => {
    this.setState({
      drawerVisible: !!flag,
    });
  };

  /**
   * 列表改变
   * @param current
   */
  handleStandardTableChange = current => {
    const { formValues } = this.state;
    const params = {
      ...formValues,
      page_no: current - 1,
    };
    this.setState({
      formValues: params,
    });
    // this.queryNodeData(params);
  };

  handleStateChange = value => {
    /* const {formValues} = this.state;
    const {form} = this.props;
    const params = {
      ...formValues,
      state: value,
    };
    this.setState({
      formValues: params
    });
    form.setFieldsValue({state:value})
    this.queryTable(params); */
  };

  operation = data => <></>;

  handlerLayerCheckChange = list => {
    this.setState({
      checkedList: list,
    });
    Object.keys(this.labelLayers).forEach(key => {
      const f = list.findIndex(val => val === key) !== -1;
      this.labelLayers[key].setVisible(f);
    });
    this.closePopup();
  };

  /**
   * 跟踪人
   * @param id
   * @param f bool 是否跟踪
   */
  track = (id, f) => {
    // this.plane.layer.setVisible(true);
    const feature = this.plane.getFeatureById(id);
    if (!feature) {
      message.warning('地图中未找到图标');
      return;
    }
    if (f) {
      this.plane.setSelectFeature(this.plane.getFeatureById(id));
    }
    this.plane.setfollow(f);
    this.setState({ isFollow: f });

    // select = this.plane.selectPlane;
    /* if (select && select.id) {
      this.showPopup({
        id: select.id,
        type: select.type,
        popupType: 'people',
        coordinate: [select.x, select.y]
      });

    } */
  };

  showPopup = ({ id, type, popupType, coordinate }) => {
    const { popup } = this.state;
    const { main } = this.props;
    if (type === 1) this.selectFeatureById(id);
    this.getLabelDetail({ id, type, popupType, coordinate });
  };

  labelDetailTime;
  labelDetailParams = {};
  getLabelDetail = ({ id, type, popupType, coordinate }) => {
    const { popup } = this.state;
    clearTimeout(this.labelDetailTime);
    this.labelDetailParams = { id, type };
    this.labelDetail(
      {
        id,
        type,
      },
      data => {
        let temp = type === 8 && type === popup.type ? popup.data : [];
        const i = _.findIndex(temp, function (o) {
          return o.id === data.id;
        });
        temp = i === -1 ? [...temp, data] : temp;
        /*if (type === 1) {
          const { treeRecord } = this.state;
          if (data.floor_id && treeRecord.floor_id !== data.floor_id) {
                  const {main: {treeData: {treeObject}}} = this.props;
                this.treeNodeChange(treeObject[data.floor_id], () => {
                  this.selectFeatureById(data.id);
                });
          }
        }*/
        if (type !== 1) {
          this.setState({
            labelPopup: {
              ...data,
              labelType: type,
            }
          }
          );
        }
        this.setState({
          popup: {
            type,
            data: [...temp],
          },
        },
          () => this.handleTargetDrawerVisible(true),
        );
        if (this.getLabelDetail) {
          this.labelDetailTime = setTimeout(() => {
            this.getLabelDetail({ id, type, popupType, coordinate });
          }, 10 * 1000);
        }
      },
    );
  };

  selectFeatureById = id => {
    const feature = this.plane.getFeatureById(id);
    if (!feature) {
      message.warning('地图中未找到图标');
      return;
    }
    this.plane.setSelectFeature(this.plane.getFeatureById(id));
  };

  closePopup = popup => {
    // this.state.popup[key] = undefined;
    /*    if (popup.type === 'people') {
          this.plane.setfollow(false);
          this.plane.selectPlane = {};
        } */
    this.handleTargetDrawerVisible(false);
    this.setState({
      popup: { type: undefined, data: [] },
      labelPopup: {}
    });
    clearTimeout(this.labelDetailTime);
  };

  routerPlayBack = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'playback/saveSearchData',
      payload: {
        id: parseInt(id),
      },
    });
    router.push('/playback');
  };

  startCameraMonitor = data => {
    const { dispatch } = this.props;
    const { videoMap } = this.state;
    if (!videoMap[data.id]) {
      videoMap[data.id] = data;
    } else {
      delete videoMap[data.id];
    }
    this.setState({
      videoMap: { ...videoMap },
    });
  };

  startCameraPlayBack = data => {
    /*    this.setState({
          videoMap: {}
        });
        this.setModalType('camera', data); */

    window.open(`http://${data.IP}/`, '_blank');
  };

  setModalType = (type, obj) => {
    this.setState({
      modalType: type,
      modalValues: obj,
    });
  };

  handleDeal = data => {
    const { dispatch } = this.props;
    Modal.confirm({
      title: '信息提示',
      content: '确定处理？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'main/deal',
          payload: {
            id: data.id,
          },
          callback: () => {
            message.success('处理成功');
            //this.closePopup();
            const { treeRecord } = this.state;
            this.fetchLabel(treeRecord.id);
            if (this.labelDetailParams.id) {
              this.getLabelDetail(this.labelDetailParams);
            }
            // this.queryNodeData();
          },
        });
      },
    });
  };

  handleFull = () => {
    // let de = document.documentElement;
    const de = document.getElementById('roots_map');

    const isFullscreen =
      document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen;
    if (!isFullscreen) {
      // 进入全屏,多重短路表达式
      (de.requestFullscreen && de.requestFullscreen()) ||
        (de.mozRequestFullScreen && de.mozRequestFullScreen()) ||
        (de.webkitRequestFullscreen && de.webkitRequestFullscreen()) ||
        (de.msRequestFullscreen && de.msRequestFullscreen());
    } else {
      // 退出全屏,三目运算符
      document.exitFullscreen
        ? document.exitFullscreen()
        : document.mozCancelFullScreen
          ? document.mozCancelFullScreen()
          : document.webkitExitFullscreen
            ? document.webkitExitFullscreen()
            : '';
    }
  };

  bindFullscreenListener = () => {
    // 监听退出全屏事件 --- chrome 用 esc 退出全屏并不会触发 keyup 事件
    document.addEventListener('webkitfullscreenchange', this.checkFull);
    document.addEventListener('mozfullscreenchange', this.checkFull);
    document.addEventListener('fullscreenchange', this.checkFull);
    document.addEventListener('MSFullscreenChange', this.checkFull);
  };

  unBindFullscreenListener = () => {
    document.removeEventListener('webkitfullscreenchange', this.checkFull);
    document.removeEventListener('mozfullscreenchange', this.checkFull);
    document.removeEventListener('fullscreenchange', this.checkFull);
    document.removeEventListener('MSFullscreenChange', this.checkFull);
  };

  checkFull = () => {
    if (!document.webkitIsFullScreen && !document.mozFullScreen && !document.msFullscreenElement) {
      this.setState({
        fullScreen: false,
      });
    } else {
      this.setState({
        fullScreen: true,
      });
    }
  };

  handleChangeLayerCheck = () => {
    this.setState({
      showLayerCheck: !this.state.showLayerCheck,
    });
  };

  handleSNSearch = value => {
    this.setState({
      formValues: {
        ...this.state.formValues,
        page_no: 0,
        SN: value,
      },
    });
  };

  render() {
    const {
      dispatch,
      main: {
        treeData: { treeObject, list },
        nodeSelectedKeys = [],
        visitorNum: { all = 0, alarm = 0, current = 0 },
        monitorData,
        data,
        floorsList,
      },
    } = this.props;
    const {
      nodeType,
      drawerVisible,
      checkedList,
      popup,
      treeRecord,
      selectedKeys,
      videoMap,
      modalType,
      modalValues,
      isFollow,
      fullScreen,
      showLayerCheck,
      labelPopup
    } = this.state;
    const videoKeys = Object.keys(videoMap);
    const tabListNoTitle = [
      {
        key: 1,
        tab: '人员',
      },
      {
        key: 2,
        tab: '摄像头',
      },
      /* {
        key: 3,
        tab: <div>报警<span style={{color: '#d5360e'}}>({alarm})</span></div>,
      }, */
    ];
    return (
      <Fragment>
        <div className={styles.main_box}>
          <div className="flex">
            <div className={styles.main_left}>
              <Card
                /*           tabList={tabListNoTitle}
                           activeTabKey={nodeType.toString()}
                           onTabChange={key => {
                             this.handleNodeTypeChange(parseInt(key));
                           }}*/
                title={
                  <div className={styles.tabs}>
                    {tabListNoTitle.map(item => {
                      return <div key={item.key}
                        className={classNames([styles.tab, { [styles.active]: nodeType === item.key }])}
                        onClick={() => this.handleNodeTypeChange(item.key)}>{item.tab}</div>;
                    })}
                  </div>
                }
                bordered={false}
                style={{ width: 320 }}
                headStyle={{ backgroundColor: '#f0f0f0', height: 56, padding: 0 }}
                bodyStyle={{
                  backgroundColor: '#fafafa',
                  paddingTop: 10,
                  height: 300,
                  overflow: 'auto',
                }}
                className={'sss'}
              >

                <CustomerTree
                  treeData={list}
                  nodeType={nodeType}
                  setTreeSelected={this.setTreeSelected}
                  defaultExpandAll
                  //  defaultSelectedKeys={nodeSelectedKeys}
                  selectedKeys={selectedKeys || nodeSelectedKeys}
                />
              </Card>
              <Card
                title={
                  <>
                    详细列表
                    <Search
                      placeholder="请输入SN号"
                      onChange={e => this.handleSNSearch(e.target.value)}
                      style={{ width: 150, marginLeft: 8 }}
                    />
                  </>
                }
                style={{ width: 320 }}
                headStyle={{ backgroundColor: '#f0f0f0', height: 56, }}
                bodyStyle={{
                  backgroundColor: '#fafafa',
                  padding: '10px 15px',
                  height: 'calc(100vh - 491px)',
                  overflow: 'auto',
                }}
              >
                <ListCardList
                  data={data}
                  nodeType={nodeType}
                  treeRecord={treeRecord}
                  onChange={this.handleStandardTableChange}
                  // setModalType={this.setModalType}
                  videoMap={videoMap}
                  handleStateChange={this.handleStateChange}
                  plane={this.plane}
                  isFollow={isFollow}
                  methods={{
                    showPopup: this.showPopup,
                    track: this.track,
                    routerPlayBack: this.routerPlayBack,
                    startCameraMonitor: this.startCameraMonitor,
                    startCameraPlayBack: this.startCameraPlayBack,
                  }}
                />
              </Card>
              {/*              <Card
                title={<CustomerSelect dataSource={treeType} value={nodeType} onChange={this.handleNodeTypeChange}/>}
                bordered={false}
                style={{width: 300}}
                headStyle={{backgroundColor: '#f0f0f0', height: 56}}
                bodyStyle={{backgroundColor: '#fafafa'}}
              >

                <CustomerTree
                  treeData={treeData.list}
                  setTreeSelected={this.setTreeSelected}
                  defaultExpandAll={true}
                  //  defaultSelectedKeys={nodeSelectedKeys}
                  selectedKeys={selectedKeys || nodeSelectedKeys}
                />
              </Card> */}
              {/* <Card title="图层显示" bordered={false} style={{width: 300, marginTop: 14}}
                    headStyle={{backgroundColor: '#f0f0f0'}} bodyStyle={{backgroundColor: '#fafafa'}}>
                <LayerCheck value={checkedList} handlerChange={this.handlerLayerCheckChange}/>
              </Card> */}
            </div>
            <div className="flex_item" style={{ position: 'relative' }}>
              {treeRecord && treeRecord.id === 1 ? (
                <div className={styles.roots_map}>
                  {/* {floorsList.map((item, index) => {
                    return <RootMap treeRecord={item} key={index}/>;
                  })} */}
                  <div
                    id="roots_map"
                    style={{ width: '100%', height: '100%', backgroundColor: '#FFF' }}
                  >
                    {fullScreen ? (
                      <div className={styles.title}>人员定位及落水识别智能管理系统</div>
                    ) : null}

                    {floorsList && floorsList.length > 0 ? (
                      <table>
                        <tr>
                          <td rowSpan={2} style={{ width: '33.333%', height: '100%' }}>
                            <RootMap
                              monitorData={monitorData}
                              checkedList={checkedList}
                              treeRecord={floorsList[0]}
                            />
                            <Button
                              type="primary"
                              className={styles.label_btn}
                              onClick={() =>
                                this.treeNodeChange(treeObject[floorsList[0].floor_id])
                              }
                            >
                              {`点击查看: ${floorsList[0].name}${floorsList[0].remark}`}{' '}
                            </Button>
                          </td>
                          <td style={{ width: '33.333%' }}>
                            <RootMap
                              monitorData={monitorData}
                              checkedList={checkedList}
                              treeRecord={floorsList[1]}
                            />
                            <Button
                              type="primary"
                              className={styles.label_btn}
                              onClick={() =>
                                this.treeNodeChange(treeObject[floorsList[1].floor_id])
                              }
                            >
                              {`点击查看: ${floorsList[1].name}${floorsList[1].remark}`}{' '}
                            </Button>
                          </td>
                          <td style={{ width: '33.333%' }}>
                            <RootMap
                              monitorData={monitorData}
                              checkedList={checkedList}
                              treeRecord={floorsList[2]}
                            />
                            <Button
                              type="primary"
                              className={styles.label_btn}
                              onClick={() =>
                                this.treeNodeChange(treeObject[floorsList[2].floor_id])
                              }
                            >
                              {`点击查看: ${floorsList[2].name}${floorsList[2].remark}`}{' '}
                            </Button>
                          </td>
                        </tr>
                        <tr>
                          <td>
                            <RootMap
                              monitorData={monitorData}
                              checkedList={checkedList}
                              treeRecord={floorsList[3]}
                            />
                            <Button
                              type="primary"
                              className={styles.label_btn}
                              onClick={() =>
                                this.treeNodeChange(treeObject[floorsList[3].floor_id])
                              }
                            >
                              {`点击查看: ${floorsList[3].name}${floorsList[3].remark}`}{' '}
                            </Button>
                          </td>
                          <td>
                            <RootMap
                              monitorData={monitorData}
                              checkedList={checkedList}
                              treeRecord={floorsList[4]}
                            />
                            <Button
                              type="primary"
                              className={styles.label_btn}
                              onClick={() =>
                                this.treeNodeChange(treeObject[floorsList[4].floor_id])
                              }
                            >
                              {`点击查看: ${floorsList[4].name}${floorsList[4].remark}`}{' '}
                            </Button>
                          </td>
                        </tr>
                      </table>
                    ) : null}
                  </div>

                  <div className={styles.fullscreen} onClick={this.handleFull}>
                    <div>
                      <Icon type="fullscreen" style={{ fontSize: 24 }} />
                    </div>
                    <span>全屏</span>
                  </div>

                  <div className={styles.layerBtnBox} onClick={this.handleChangeLayerCheck}>
                    <div>
                      <IconFont type="icon-tuceng" style={{ fontSize: 24 }} />
                    </div>
                    <span>图层</span>
                  </div>
                  {showLayerCheck ? (
                    <LayerCheck
                      value={checkedList}
                      handlerChange={this.handlerLayerCheckChange}
                      style={{
                        right: 70,
                        top: 74,
                      }}
                    />
                  ) : null}
                </div>
              ) : null}
              <div className={styles.right_title}>
                <div className={styles.right_title_content}>
                  当前实时人数：<span style={{ color: '#037fbf' }}>{current}</span>人
                </div>
                <div className={styles.right_title_content}>
                  总客流量：<span style={{ color: '#ffbc00' }}>{all}</span>人次
                </div>
                <div className={styles.right_title_content}>
                  报警：<span style={{ color: '#d5360e' }}>{alarm}</span>
                </div>
              </div>
              <div id="map" style={{ width: '100%', height: '100%' }} />
              {labelPopup.id && this.map ? <LabelPopup popup={labelPopup} map={this.map} /> : null}


              {videoKeys.length > 0 ? (
                <div className={styles.video_box}>
                  <Row gutter={24}>
                    {videoKeys.map(key => {
                      const data = videoMap[key];
                      return (
                        <Suspense fallback={<PageLoading />}>
                          <Col span={8} style={{ marginBottom: 8 }}>
                            <div className={styles.title}>
                              {data.name} - 实时画面
                              <a
                                className={styles.close}
                                onClick={() => this.startCameraMonitor(data)}
                              >
                                <Icon type="close" />
                              </a>
                            </div>
                            {data && data.url ?
                              <iframe src={data.url} frameborder={0} style={{ width: 280, height: 210 }} />
                              : ''}

                          </Col>
                        </Suspense>
                      );
                    })}
                  </Row>
                </div>
              ) : null}
              <LayerCheck value={checkedList} handlerChange={this.handlerLayerCheckChange} />
            </div>
          </div>
          {popup ? (
            <Drawer
              title={
                <span style={{ color: popup.type === 10 ? '#d5360e' : '' }}>{`${
                  treeTypeObj[popup !== undefined ? popup.type : '']
                  }信息`}</span>
              }
              placement="right"
              mask={false}
              onClose={() => this.closePopup()}
              visible={drawerVisible}
              getContainer={false}
              width={350}
              style={{ position: 'absolute' }}
              headerStyle={{ backgroundColor: '#f0f0f0', height: 56 }}
              bodyStyle={{
                backgroundColor: '#fafafa',
                padding: '10px 15px',
                color: popup.type === 10 ? '#d5360e' : '',
              }}
              drawerStyle={{ backgroundColor: '#fafafa' }}
            >
              {popup && drawerVisible ? (
                <>
                  <ListCardDetail
                    data={popup.data}
                    nodeType={popup.type}
                    onChange={this.handleStandardTableChange}
                    // setModalType={this.setModalType}
                    plane={this.plane}
                    isFollow={isFollow}
                    videoMap={videoMap}
                    handleStateChange={this.handleStateChange}
                    operation={this.operation}
                    methods={{
                      track: this.track,
                      routerPlayBack: this.routerPlayBack,
                      startCameraMonitor: this.startCameraMonitor,
                      startCameraPlayBack: this.startCameraPlayBack,
                      handleDeal: this.handleDeal,
                    }}
                  />
                </>
              ) : null}
            </Drawer>
          ) : null}
        </div>

        {modalType === 'camera' ? (
          <Suspense fallback={<PageLoading />}>
            <CamerabackForm
              title="驾驶员信息"
              afterClose={this.setModalType}
              values={modalValues}
              callback={this.modalCallback}
            />
          </Suspense>
        ) : null}
      </Fragment>
    );
  }
}

export default Index;